// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */

	//简单的取出子分类的函数
	async getChild(id){
		//取出子id
		let child_arr = [];
		let child = await this.model('or_subjecttype').where({pid:id}).getField('id');
		if (!think.isEmpty(child)) {
			for (var i = child.length - 1; i >= 0; i--) {
				child_arr.push(child[i]);
				child_arr = child_arr.concat(await this.getChild(child[i]));
			};
		};
		return child_arr;	
	}

	//制作inarray函数
	inArray(id,array){
		if (!think.isEmpty(array)) {
			for (var i = 0; i < array.length; i++) {
				if (array[i] == id) {
					return true;
				};
			};
		};
		return false;
	}

	async subjectlistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.userinfo.departmentid;

		let data = await this.model('or_subject')
				.alias('s')
				.field('s.*,b.name as bname,c.name as cname')
				.join('`think_or_brand` b on b.id=s.brandid')
				.join('`think_or_subjectcategory` c on c.id=s.categoryid')
				.page(pages, limits)
				.order('s.id DESC')
				.where({'s.departmentid':shopid, 's.isdisable':zt, 's.name|s.remarks|b.name|c.name':['like','%'+search+'%']})
				.countSelect();

		return this.json(data);
	}

	async getcategoryAction(){
		let categoryid = JSON.parse(this.post('id'));
		let data = [];
		if (!think.isEmpty(categoryid)) {
			data = await this.model('or_subjectcategory').where({id:['IN',categoryid]}).select();
		}
		return this.json(data);
	}

	// 新增、编辑项目
	async addeditAction(){
		let data = this.post();
		let orid = this.userinfo.departmentid;
		let addtime = Math.round(new Date().valueOf()/1000);

		let repeat = await this.model('or_subject').where('departmentid='+orid+' AND (name="'+data.name+'" OR number="'+data.number+'") AND id!="'+data.id+'"').select();

		if (!think.isEmpty(repeat)) return this.fail('名称或编号重复');

		if (data.xstdtype==1) {
			data.xspercent = Number(data.xspercent/100).toFixed(2);
			data.xsfixed = 0;
		} else {
			data.xspercent = 0;
		}

		if (data.sgtdtype==1) {
			data.sgpercent = Number(data.sgpercent/100).toFixed(2);
			data.sgfixed = 0;
		} else {
			data.sgpercent = 0;
		}

		if (data.khtdtype==1) {
			data.khpercent = Number(data.khpercent/100).toFixed(2);
			data.khfixed = 0;
		} else {
			data.khpercent = 0;
		}

		// 编辑项目
		if (data.id*1) {
			/*let shiyong = await this.ispull(data.id);
			if (!think.isEmpty(shiyong)) {
				return this.fail(shiyong.msg)
			}*/
			let upd = await this.model('or_subject').update(data);
			return upd?this.success('编辑成功'):this.fail('编辑失败');
		}
		
		// 添加项目
		let add = {
			name: data.name,
			departmentid: orid,
			categoryid: data.categoryid,
			brandid: data.brandid,
			price: data.price,
			usetime: data.usetime,
			remarks: data.remarks,
			addtime: addtime,
			number: data.number,
			xstdtype: data.xstdtype,
			xspercent: data.xspercent,
			xsfixed: data.xsfixed,
			sgtdtype: data.sgtdtype,
			sgpercent: data.sgpercent,
			sgfixed: data.sgfixed,
			khtdtype: data.khtdtype,
			khpercent: data.khpercent,
			khfixed: data.khfixed,
		}
		//写入数据库
		let res = await this.model('or_subject').add(add);

		return res?this.success('添加成功'):this.fail('添加失败');
	}

	// 选择项目
	async selectsubjectAction(){
		let cardid = this.get('cardid');
		let selectsub = await this.model('or_subject')
			.alias('s')
			.join('`think_or_subjectcategory` c on c.id = s.categoryid')
			.field('s.*,c.name as cname')
			.where({'s.departmentid':this.userinfo.departmentid,'s.isdisable':0})
			.select();
		let validity = await this.model('or_card').where({id:cardid}).getField('validity');
		for (var i = 0, selectlen = selectsub.length; i < selectlen; i++) {
			selectsub[i]['validity'] = validity[0];
		}
		let relist = {
            "draw": '',
            "data": selectsub,
            "breadcrumb":''
    	}
		return this.json(relist);
	}

	// 停用或启用项目
	async subjectstatusAction(){
		let id = this.post('id');
		let st = this.post('st');
		let shiyong = await this.ispull(id);
		if (!think.isEmpty(shiyong)) {
			return this.fail(shiyong.msg)
		}
		let res = await this.model('or_subject').where({id:id}).update({isdisable:st});
		if (st*1) {
			return res?this.success('停用成功'):this.fail('停用失败');
		} else {
			return res?this.success('启用成功'):this.fail('启用失败');
		}
	}

	// 获取机构下的项目分类列表
	async subjectcategorylistAction(){
		let shopid = this.userinfo.departmentid;
		let clist = await this.model('or_subjectcategory').where({departmentid:shopid,pid:['!=',0],isdisable:0}).select();
		let blist = await this.model('or_brand').where({departmentid:shopid}).select();
		let data = {
			cs : clist,
			bs : blist
		}
		return this.json(data);
	}

	async getsubjectcategorylistAction(){
		let shopid = this.userinfo.departmentid;
		let slist = await this.model('or_subjectcategory').where({departmentid:shopid,pid:['!=',0]}).select();
		let blist = await this.model('or_brand').where({departmentid:shopid}).select();
		let data = {
			cs : slist,
			bs : blist
		}
		return this.json(data);
	}

	// 如果当前项目被下属分店拉取，则机构不能操作当前项目
	async ispull(subjectid){
		let isuse = await this.model('or_shop_subject').where({subjectid: subjectid}).select();
		if (!think.isEmpty(isuse)) return {msg:'当前项目以被分店拉取'};
		else return false;
	}
}